﻿#include "baiduspeech.h"
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

BaiduSpeech::BaiduSpeech(QObject *parent, const QString& appkey, const QString& secret) :
    QObject(parent),
    _appkey(appkey),
    _secret(secret)
{
    _client = new QNetworkAccessManager(this);
    getToken();
}

void BaiduSpeech::getToken()
{
    QUrlQuery params;
    params.addQueryItem("grant_type", "client_credentials");
    params.addQueryItem("client_id", _appkey);
    params.addQueryItem("client_secret", _secret);

    QNetworkRequest request(QUrl("http://openapi.baidu.com/oauth/2.0/token"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    _client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    connect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_tokenReply);
}

void BaiduSpeech::on_tokenReply(QNetworkReply* reply)
{
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    _token = json["access_token"].toString();
    disconnect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_tokenReply);
    reply->deleteLater();
}

void BaiduSpeech::doASR(const QByteArray data)
{
    _msg.clear();

    QUrlQuery params;
    params.addQueryItem("dev_pid", "1537");//识别语言及模型选择
    params.addQueryItem("token", _token);
    params.addQueryItem("cuid", "123456");//用户唯一标识

    QUrl api("http://vop.baidu.com/server_api");
    api.setQuery(params);
    QNetworkRequest request(api);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "audio/wav;rate=16000");
    connect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_ASRReply);

    _client->post(request, data);
}

void BaiduSpeech::on_ASRReply(QNetworkReply* reply)
{
    disconnect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_ASRReply);
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    //qDebug() << QJsonDocument(json).toJson();

    if (json["err_no"].toInt()) {
        qDebug() << json["err_no"].toInt() << json["err_msg"].toString();
    }
    else {
        _msg = "";
        QJsonArray a = json["result"].toArray();
        for (int i = 0; i < a.size(); i++) {
            _msg += a[i].toString();
        }
    }
    reply->deleteLater();
    emit doneASR();
}

void BaiduSpeech::doTTS(const QString data)
{
    _audio.clear();

    QUrlQuery params;
    params.addQueryItem("tex", data);//合成的文本，使用UTF-8编码。
    params.addQueryItem("tok", _token);
    params.addQueryItem("cuid", "123456");//用户唯一标识
    params.addQueryItem("ctp", "1");//客户端类型选择，web端填写固定值1
    params.addQueryItem("lan", "zh");//语言选择,目前只有中英文混合模式，填写固定值zh
    params.addQueryItem("aue", "4");//QAudioOutput 需要使用PCM 16K

    QNetworkRequest request(QUrl("http://tsn.baidu.com/text2audio"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    connect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_TTSReply);

    _client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
}

void BaiduSpeech::on_TTSReply(QNetworkReply* reply)
{
    disconnect(_client, &QNetworkAccessManager::finished, this, &BaiduSpeech::on_TTSReply);
    _audio = reply->readAll();
    emit doneTTS();
}

QString BaiduSpeech::message()
{
    return _msg;
}

QByteArray BaiduSpeech::audio()
{
    return _audio;
}
